﻿using System;
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.FileProviders;
using Microsoft.Net.Http.Headers;
using ZilLion.Service.Core.ConfigManager.Manager;
using ZilLion.Service.Core.Infrastructure.Middleware.Error;
using ZilLion.Service.Core.Ioc;
using ZilLion.Service.Core.Snowflake;
using ZilLion.Service.Core.Starter.Config;

namespace ZilLion.Service.Core.Starter.Extention
{
    public static class ZilLionApplicationBuilderExtensions
    {
        /// <summary>
        ///     初始化特殊路由
        /// </summary>
        public static void UseZilLionSpecialRoute(this IApplicationBuilder app)
        {
            app.UseMvc(routes =>
            {
                foreach (var loader in IocConfig.ComponentLoaderCache.Values)
                    loader.ConfigureSpecialRoute(routes); //注册各个模块的特殊理由,接入代理功能等
            });

            app.UseMvcWithDefaultRoute();
        }

        /// <summary>
        ///     跨域
        /// </summary>
        /// <param name="app"></param>
        public static void UseZilLionCors(this IApplicationBuilder app)
        {
            app.UseCors(builder =>
                builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());

            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor |
                                   ForwardedHeaders.XForwardedProto
            });
        }

        /// <summary>
        ///     配置swagger
        /// </summary>
        /// <param name="app"></param>
        public static void UseZilLionApiDoc(this IApplicationBuilder app)
        {
            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json",
                    ZilLionConfigurationManager.GetConfigInstance<ApiDocConfig>().ApiDocTitle ?? "纵联科技服务接口文档 v1");
                options.ShowJsonEditor();
            });
        }

        /// <summary>
        ///     启用单页应用的静态文件服务器
        /// </summary>
        /// <param name="app"></param>
        public static void UseZilLionStaticService(this IApplicationBuilder app)
        {
            var contentRoot = AppDomain.CurrentDomain.BaseDirectory;
            var viewspath = Path.Combine(contentRoot, "views");
            var staticspath = Path.Combine(contentRoot, "views", "static");

            if (Directory.Exists(viewspath) && Directory.Exists(staticspath))
            {
                IFileProvider fileProvider = new PhysicalFileProvider(viewspath);
                IFileProvider staticProvider = new PhysicalFileProvider(staticspath);

                app.UseDefaultFiles(new DefaultFilesOptions
                {
                    RequestPath = PathString.Empty,
                    FileProvider = fileProvider
                });

                app.UseStaticFiles(new StaticFileOptions
                {
                    FileProvider = staticProvider,
                    RequestPath = "/static",
                    OnPrepareResponse = context =>
                    {
                        const int durationInSeconds = 60 * 60;
                        context.Context.Response.Headers[HeaderNames.CacheControl] =
                            "public,max-age=" + durationInSeconds;

                        //if (context.Context.Response.ContentType == "application/x-gzip")
                        //{
                        //    if (context.Context.Response.Headers.File.Name.EndsWith("js.gz"))
                        //    {
                        //        context.Context.Response.Headers.ContentType = new MediaTypeHeaderValue("application/javascript");
                        //    }
                        //    else if (context.File.Name.EndsWith("css.gz"))
                        //    {
                        //        context.Context.Response.Headers.ContentType = new MediaTypeHeaderValue("text/css");
                        //    }

                        //    context.Context.Response.Headers.Add("Content-Encoding", "gzip");
                        //}
                    }
                });
                app.UseStaticFiles(new StaticFileOptions
                {
                    FileProvider = fileProvider,
                    RequestPath = PathString.Empty
                });
            }
        }

        /// <summary>
        ///     必配置项
        /// </summary>
        /// <param name="app"></param>
        public static void UseZilLionCore(this IApplicationBuilder app)
        {
            app.UseErrorHandling(); //错误处理
            app.UseZilLionCors(); //跨域
            app.UseZilLionApiDoc(); //api文档
            app.UseMvc(); //支持mvc
            app.UseZilLionSpecialRoute(); //特殊路由注册
            SnowflakeIdCreater.Instance().Init(); //初始化全局雪花ID生成器
        }
    }
}